package javabase.concurrent;

import java.util.Random;

public class TimeoutWaitExample {

    private static final Object lock = new Object();
    private static boolean ready = false;

    protected static final Random RANDOM = new Random();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            @Override
            public void run() {
            for (;;) {
                synchronized (lock) {
                    ready = RANDOM.nextInt(1000) < 20;
                    if (ready) {
                        lock.notify();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }
        };
        t.setDaemon(true);
        t.start();
        waiter(1000);
    }

    private static void waiter(final long timeout) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException();
        }
        long start = System.currentTimeMillis();
        long waitTime;
        long now;
        synchronized (lock) {
            while (!ready) {
                now = System.currentTimeMillis();
                // 计算剩余等待时间
                waitTime = timeout - (now - start);
                System.out.printf("remain time to wait : %s", waitTime);
                System.out.println();
                if (waitTime <= 0) {
                    break;
                }
                lock.wait(timeout);
            }
            if (ready) {
                action();
            } else {
                System.out.println("wait time out");
            }
        }

    }

    private static void action() {
        System.out.println("do some action");
    }

}
